<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件操作平台 - 高级接口演示</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3a56d4;
            --success: #06d6a0;
            --warning: #ffd166;
            --danger: #ef476f;
            --dark: #1e1e2e;
            --light: #f8f9fa;
            --gray: #adb5bd;
            --border: #dee2e6;
            --card-bg: #ffffff;
            --body-bg: #f0f2f5;
            --text: #343a40;
            --text-light: #6c757d;
            --tooltip-bg: #495057;
        }

        .dark-mode {
            --dark: #121212;
            --light: #1e1e2e;
            --border: #444;
            --card-bg: #2d2d2d;
            --body-bg: #121212;
            --text: #e0e0e0;
            --text-light: #a0a0a0;
            --tooltip-bg: #343a40;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            transition: background-color 0.3s, color 0.3s, border-color 0.3s;
        }

        body {
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            background-color: var(--body-bg);
            color: var(--text);
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
            background-image: radial-gradient(circle at 15% 50%, rgba(67, 97, 238, 0.05) 0%, transparent 25%),
                              radial-gradient(circle at 85% 30%, rgba(6, 214, 160, 0.05) 0%, transparent 25%);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 0;
            border-bottom: 1px solid var(--border);
            margin-bottom: 30px;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--primary);
        }

        .logo i {
            font-size: 2.2rem;
            animation: pulse 2s infinite;
        }

        .header-controls {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .theme-switch {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 20px;
            padding: 5px;
            display: flex;
            cursor: pointer;
        }

        .theme-switch-btn {
            padding: 5px 15px;
            border-radius: 15px;
            border: none;
            background: transparent;
            color: var(--text);
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }

        .theme-switch-btn.active {
            background: var(--primary);
            color: white;
        }

        .dashboard {
            display: grid;
            grid-template-columns: 1fr 350px;
            gap: 25px;
        }

        .main-content {
            display: grid;
            gap: 25px;
        }

        .operations {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 25px;
        }

        .operation-card {
            background: var(--card-bg);
            border-radius: 16px;
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            border: 1px solid var(--border);
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .operation-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
        }

        .card-header {
            padding: 18px 20px;
            background: rgba(67, 97, 238, 0.08);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .card-header i {
            font-size: 1.4rem;
            color: var(--primary);
            width: 36px;
            height: 36px;
            background: rgba(67, 97, 238, 0.15);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .card-header h3 {
            font-size: 1.2rem;
            font-weight: 600;
        }

        .card-body {
            padding: 20px;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text);
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .form-group label i {
            width: 20px;
            text-align: center;
            color: var(--primary);
        }

        input, textarea, select {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid var(--border);
            border-radius: 10px;
            background: var(--card-bg);
            color: var(--text);
            font-size: 1rem;
            transition: border-color 0.3s, box-shadow 0.3s;
        }

        textarea {
            min-height: 100px;
            resize: vertical;
            font-family: inherit;
        }

        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px 25px;
            border-radius: 10px;
            border: none;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
            box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
        }

        .btn-primary:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(67, 97, 238, 0.4);
        }

        .btn-block {
            display: block;
            width: 100%;
            padding: 14px;
        }

        .loading .btn-text {
            visibility: hidden;
            position: relative;
        }

        .loading::after {
            content: "";
            position: absolute;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
            left: calc(50% - 10px);
        }

        .result-area {
            margin-top: 20px;
            padding: 15px;
            border-radius: 10px;
            font-size: 0.95rem;
            color: var(--text);
            display: none;
        }

        .result-area.success {
            display: block;
            background: rgba(6, 214, 160, 0.1);
            border: 1px solid rgba(6, 214, 160, 0.3);
        }

        .result-area.error {
            display: block;
            background: rgba(239, 71, 111, 0.1);
            border: 1px solid rgba(239, 71, 111, 0.3);
        }

        .result-area.info {
            display: block;
            background: rgba(67, 97, 238, 0.1);
            border: 1px solid rgba(67, 97, 238, 0.3);
        }

        .result-code {
            font-family: 'Fira Code', monospace;
            background: rgba(0, 0, 0, 0.05);
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
            overflow-x: auto;
            font-size: 0.9rem;
        }

        .sidebar {
            display: flex;
            flex-direction: column;
            gap: 25px;
        }

        .file-preview {
            background: var(--card-bg);
            border-radius: 16px;
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            border: 1px solid var(--border);
        }

        .preview-header {
            display: flex;
            justify-content: space-between;
            padding: 18px 20px;
            border-bottom: 1px solid var(--border);
        }

        .preview-content {
            padding: 20px;
            min-height: 250px;
            max-height: 350px;
            overflow-y: auto;
        }

        .file-info {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .file-info-item {
            display: flex;
            justify-content: space-between;
            padding-bottom: 10px;
            border-bottom: 1px dashed var(--border);
        }

        .file-info-label {
            color: var(--text-light);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .file-info-value {
            font-weight: 500;
        }

        .no-file {
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: var(--text-light);
            text-align: center;
            padding: 30px;
        }

        .no-file i {
            font-size: 3rem;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .history-card {
            background: var(--card-bg);
            border-radius: 16px;
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            border: 1px solid var(--border);
        }

        .history-list {
            padding: 10px 0;
            max-height: 300px;
            overflow-y: auto;
        }

        .history-item {
            padding: 12px 20px;
            display: flex;
            gap: 15px;
            align-items: center;
            border-bottom: 1px solid var(--border);
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .history-item:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }

        .history-item:last-child {
            border-bottom: none;
        }

        .history-icon {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .upload .history-icon {
            background: rgba(67, 97, 238, 0.15);
            color: var(--primary);
        }

        .create .history-icon {
            background: rgba(6, 214, 160, 0.15);
            color: var(--success);
        }

        .append .history-icon {
            background: rgba(255, 209, 102, 0.15);
            color: #e6b400;
        }

        .history-details {
            flex: 1;
            min-width: 0;
        }

        .history-title {
            font-weight: 500;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .history-time {
            font-size: 0.8rem;
            color: var(--text-light);
        }

        .tooltip {
            position: relative;
            display: inline-block;
        }

        .tooltip .tooltip-text {
            visibility: hidden;
            width: 200px;
            background-color: var(--tooltip-bg);
            color: white;
            text-align: center;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 0.9rem;
            font-weight: normal;
        }

        .tooltip:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }

        @media (max-width: 900px) {
            .dashboard {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 600px) {
            .operations {
                grid-template-columns: 1fr;
            }
            
            header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
            
            .header-controls {
                justify-content: center;
            }
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }

        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-connected {
            background-color: var(--success);
        }

        .status-disconnected {
            background-color: var(--danger);
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="logo">
                <i class="fas fa-file-code"></i>
                <span>文件操作平台</span>
            </div>
            <div class="header-controls">
                <div class="tooltip">
                    <span id="connectionStatus"><span class="status-indicator status-connected"></span>已连接</span>
                    <span class="tooltip-text">服务器状态: 正常运行<br>API: http://localhost:3300</span>
                </div>
                <div class="theme-switch">
                    <button class="theme-switch-btn active" id="light-theme">亮色</button>
                    <button class="theme-switch-btn" id="dark-theme">暗色</button>
                </div>
            </div>
        </header>

        <div class="dashboard">
            <div class="main-content">
                <div class="operations">
                    <!-- 文件上传模块 -->
                    <div class="operation-card">
                        <div class="card-header">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <h3>文件上传</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="fileInput"><i class="fas fa-file"></i> 选择文件</label>
                                <input type="file" id="fileInput">
                            </div>
                            <div class="form-group">
                                <label for="targetFolder"><i class="fas fa-folder"></i> 目标文件夹</label>
                                <select id="targetFolder">
                                    <option value="/documents">文档</option>
                                    <option value="/images">图片</option>
                                    <option value="/music">音乐</option>
                                    <option value="/videos">视频</option>
                                </select>
                            </div>
                            <button class="btn btn-primary btn-block" id="uploadBtn" onclick="handleUpload()">
                                <span class="btn-text"><i class="fas fa-upload"></i> 上传文件</span>
                            </button>
                            <div class="result-area" id="uploadResult"></div>
                        </div>
                    </div>

                    <!-- 文件创建模块 -->
                    <div class="operation-card">
                        <div class="card-header">
                            <i class="fas fa-file-medical"></i>
                            <h3>创建新文件</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="fileName"><i class="fas fa-font"></i> 文件名称</label>
                                <input type="text" id="fileName" placeholder="例如：report.txt">
                            </div>
                            <div class="form-group">
                                <label for="fileType"><i class="fas fa-code"></i> 文件类型</label>
                                <select id="fileType">
                                    <option value="text">文本文件 (.txt)</option>
                                    <option value="json">JSON 文件 (.json)</option>
                                    <option value="csv">CSV 文件 (.csv)</option>
                                    <option value="markdown">Markdown (.md)</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="fileContent"><i class="fas fa-file-alt"></i> 文件内容</label>
                                <textarea id="fileContent" placeholder="输入文件内容..."></textarea>
                            </div>
                            <button class="btn btn-primary btn-block" id="createBtn" onclick="createNewFile()">
                                <span class="btn-text"><i class="fas fa-plus-circle"></i> 创建文件</span>
                            </button>
                            <div class="result-area" id="createResult"></div>
                        </div>
                    </div>
                </div>
                
                <!-- 文件追加模块 -->
                <div class="operation-card">
                    <div class="card-header">
                        <i class="fas fa-edit"></i>
                        <h3>文件追加</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="fileToAppend"><i class="fas fa-file-alt"></i> 选择文件</label>
                            <select id="fileToAppend">
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="appendContent"><i class="fas fa-pen"></i> 追加内容</label>
                            <textarea id="appendContent" placeholder="输入要追加的内容..."></textarea>
                        </div>
                        <button class="btn btn-primary btn-block" id="appendBtn" onclick="appendToFile()">
                            <span class="btn-text"><i class="fas fa-save"></i> 保存内容</span>
                        </button>
                        <div class="result-area" id="appendResult"></div>
                    </div>
                </div>
            </div>

            <div class="sidebar">
                <!-- 文件预览模块 -->
                <div class="file-preview">
                    <div class="preview-header">
                        <h3><i class="fas fa-file-alt"></i> 文件预览</h3>
                    </div>
                    <div class="preview-content">
                        <div class="no-file" id="noFilePreview">
                            <i class="fas fa-file-alt"></i>
                            <p>暂无文件预览</p>
                            <p class="small">上传或创建文件后，内容将显示在这里</p>
                        </div>
                        <div id="filePreview" style="display: none;">
                            <div class="file-info">
                                <div class="file-info-item">
                                    <span class="file-info-label"><i class="fas fa-file-signature"></i> 文件名：</span>
                                    <span class="file-info-value" id="previewFileName">-</span>
                                </div>
                                <div class="file-info-item">
                                    <span class="file-info-label"><i class="fas fa-code"></i> 文件类型：</span>
                                    <span class="file-info-value" id="previewFileType">-</span>
                                </div>
                                <div class="file-info-item">
                                    <span class="file-info-label"><i class="fas fa-weight-hanging"></i> 大小：</span>
                                    <span class="file-info-value" id="previewFileSize">-</span>
                                </div>
                                <div class="file-info-item">
                                    <span class="file-info-label"><i class="fas fa-clock"></i> 最后修改：</span>
                                    <span class="file-info-value" id="previewFileModified">-</span>
                                </div>
                            </div>
                            <div class="file-content-preview">
                                <h4 style="margin: 20px 0 10px;"><i class="fas fa-eye"></i> 内容预览：</h4>
                                <div id="fileContentPreview" class="result-code"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 操作历史模块 -->
                <div class="history-card">
                    <div class="preview-header">
                        <h3><i class="fas fa-history"></i> 最近操作</h3>
                    </div>
                    <div class="history-list" id="historyList">
                        <div class="history-item upload">
                            <div class="history-icon">
                                <i class="fas fa-cloud-upload-alt"></i>
                            </div>
                            <div class="history-details">
                                <div class="history-title">上传了财务报告.docx</div>
                                <div class="history-time">2023-07-20 14:30</div>
                            </div>
                        </div>
                        <div class="history-item create">
                            <div class="history-icon">
                                <i class="fas fa-file-medical"></i>
                            </div>
                            <div class="history-details">
                                <div class="history-title">创建了 config.json</div>
                                <div class="history-time">2023-07-20 11:15</div>
                            </div>
                        </div>
                        <div class="history-item append">
                            <div class="history-icon">
                                <i class="fas fa-edit"></i>
                            </div>
                            <div class="history-details">
                                <div class="history-title">更新了 notes.md</div>
                                <div class="history-time">2023-07-19 16:45</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 主题切换功能
        document.getElementById('light-theme').addEventListener('click', function() {
            document.body.classList.remove('dark-mode');
            this.classList.add('active');
            document.getElementById('dark-theme').classList.remove('active');
        });
        
        document.getElementById('dark-theme').addEventListener('click', function() {
            document.body.classList.add('dark-mode');
            this.classList.add('active');
            document.getElementById('light-theme').classList.remove('active');
        });

        // 模拟文件预览功能
        document.getElementById('fileInput').addEventListener('change', function(e) {
            if (e.target.files.length > 0) {
                const file = e.target.files[0];
                updateFilePreview(file.name, file.type, formatFileSize(file.size), new Date().toLocaleString(), "文件内容预览将在上传后显示");
            }
        });

        document.getElementById('fileContent').addEventListener('input', function() {
            if (this.value.trim() !== '') {
                const fileName = document.getElementById('fileName').value || '新文件';
                updateFilePreview(fileName, getFileType(), '0 KB', new Date().toLocaleString(), this.value);
            }
        });

        document.getElementById('fileName').addEventListener('input', function() {
            if (document.getElementById('fileContent').value.trim() !== '') {
                updateFilePreview(this.value || '新文件', getFileType(), '0 KB', new Date().toLocaleString(), document.getElementById('fileContent').value);
            }
        });

        function getFileType() {
            const type = document.getElementById('fileType').value;
            const types = {
                'text': '文本文件 (.txt)',
                'json': 'JSON 文件 (.json)',
                'csv': 'CSV 文件 (.csv)',
                'markdown': 'Markdown (.md)'
            };
            return types[type] || 'Unknown';
        }

        function updateFilePreview(name, type, size, modified, content) {
            document.getElementById('noFilePreview').style.display = 'none';
            document.getElementById('filePreview').style.display = 'block';
            document.getElementById('previewFileName').textContent = name;
            document.getElementById('previewFileType').textContent = type;
            document.getElementById('previewFileSize').textContent = size;
            document.getElementById('previewFileModified').textContent = modified;
            document.getElementById('fileContentPreview').textContent = content;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 登录功能
        (function () {
            login();
        }());
        
        var token = '';
        
        function login() {
            // 模拟登录成功
            fetch('http://localhost:3300/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: 'admin',
                    password: '123456'
                })
            }).then(res => res.json()).then(res => {
                console.log('登录成功，token：', res.data.token);
                if (res.code === 200 && res.data.token) {
                    token = res.data.token;
                    document.getElementById('connectionStatus').innerHTML = 
                        '<span class="status-indicator status-connected"></span>已连接';
                } else {
                    document.getElementById('connectionStatus').innerHTML = 
                        '<span class="status-indicator status-disconnected"></span>未连接';
                }
                getFileList();
            }).catch(error => {
                console.error('登录失败:', error);
                document.getElementById('connectionStatus').innerHTML = 
                    '<span class="status-indicator status-disconnected"></span>连接失败';
            });
        }
        function getFileList() { 
            fetch('http://localhost:3300/api/listFiles', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            }).then(res => res.json()).then(res => {
              let fileToAppend = document.getElementById('fileToAppend');
              let fileList = res.data;
              fileToAppend.innerHTML = '';
              fileList.forEach(file => {
                let option = document.createElement('option');
                option.value = file;
                option.text = file;
                fileToAppend.appendChild(option);
              });

            }).catch(error => {
              console.error('获取文件列表失败:', error);
            });
        }

        // 设置按钮加载状态
        function setButtonLoading(buttonId, isLoading) {
            const button = document.getElementById(buttonId);
            if (isLoading) {
                button.classList.add('loading');
                button.disabled = true;
            } else {
                button.classList.remove('loading');
                button.disabled = false;
            }
        }

        // 文件上传处理
        async function handleUpload() {
            const fileInput = document.getElementById('fileInput');
            const resultArea = document.getElementById('uploadResult');
            const targetFolder = document.getElementById('targetFolder').value;
            
            if (!fileInput.files[0]) {
                showResult(resultArea, '请选择要上传的文件', 'error');
                return;
            }
            
            const file = fileInput.files[0];
            setButtonLoading('uploadBtn', true);
            showResult(resultArea, `正在上传 ${file.name} 到 ${targetFolder}...`, 'info');
            
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                const response = await fetch('http://localhost:3300/api/upload', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    showResult(resultArea, `文件上传成功！<br>路径: ${data.path}`, 'success');
                    addHistoryItem('upload', `上传了 ${file.name}`, file.type);
                    updateFilePreview(file.name, file.type, formatFileSize(file.size), new Date().toLocaleString(), `${file.name}的内容预览`);
                } else {
                    showResult(resultArea, '文件上传失败: ' + (data.message || '未知错误'), 'error');
                }
            } catch (error) {
                showResult(resultArea, '上传请求失败: ' + error.message, 'error');
            } finally {
                setButtonLoading('uploadBtn', false);
            }
        }

        // 创建新文件
        async function createNewFile() {
            const fileName = document.getElementById('fileName').value.trim();
            const fileType = document.getElementById('fileType').value;
            const content = document.getElementById('fileContent').value.trim();
            const resultArea = document.getElementById('createResult');
            
            if (!fileName) {
                showResult(resultArea, '请输入文件名', 'error');
                return;
            }
            
            if (!content) {
                showResult(resultArea, '请输入文件内容', 'error');
                return;
            }
            
            const fullFileName = `${fileName}.${getExtension(fileType)}`;
            setButtonLoading('createBtn', true);
            showResult(resultArea, `正在创建文件 ${fullFileName}...`, 'info');
            
            try {
                const response = await sendRequest('/api/createFile', 'POST', {
                    fileType: fileType,
                    content: content
                });
                
                if (response.code === 200) {
                    showResult(resultArea, `文件创建成功！<br>路径: ${response.data.path}`, 'success');
                    addHistoryItem('create', `创建了 ${fullFileName}`, fileType);
                    updateFilePreview(fullFileName, getFileType(), formatFileSize(content.length * 2), new Date().toLocaleString(), content);
                } else {
                    showResult(resultArea, `创建失败: ${response.message}`, 'error');
                }
            } catch (error) {
                showResult(resultArea, '请求失败: ' + error.message, 'error');
            } finally {
                setButtonLoading('createBtn', false);
                getFileList();
            }
        }
        
        function getExtension(type) {
            const extensions = {
                'text': 'txt',
                'json': 'json',
                'csv': 'csv',
                'markdown': 'md'
            };
            return extensions[type] || 'txt';
        }

        // 追加文件内容
        async function appendToFile() {
            const fileName = document.getElementById('fileToAppend').value;
            const content = document.getElementById('appendContent').value.trim();
            const resultArea = document.getElementById('appendResult');
            
            if (!fileName) {
                showResult(resultArea, '请选择文件', 'error');
                return;
            }
            
            if (!content) {
                showResult(resultArea, '请输入要追加的内容', 'error');
                return;
            }
            
            setButtonLoading('appendBtn', true);
            showResult(resultArea, `正在更新文件 ${fileName}...`, 'info');
            
            try {
                const response = await sendRequest('/api/writeFile', 'POST', {
                    filename: fileName,
                    content: content
                });
                
                if (response.code === 200) {
                    showResult(resultArea, `文件内容追加成功！<br>文件大小: ${response.data.size}字节`, 'success');
                    addHistoryItem('append', `更新了 ${fileName}`, 'text');
                    
                    // 更新预览内容
                    const currentContent = document.getElementById('fileContentPreview').textContent;
                    document.getElementById('fileContentPreview').textContent = currentContent + '\n\n' + content;
                } else {
                    showResult(resultArea, `操作失败: ${response.message}`, 'error');
                }
            } catch (error) {
                showResult(resultArea, '请求失败: ' + error.message, 'error');
            } finally {
                setButtonLoading('appendBtn', false);
            }
        }

        // 通用请求处理函数
        async function sendRequest(url, method, body) {
            try {
                const response = await fetch(`http://localhost:3300${url}`, {
                    method: method,
                    headers: { 
                        'Content-Type': 'application/json', 
                        'Authorization': token 
                    },
                    body: JSON.stringify(body)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                
                return await response.json();
            } catch (error) {
                throw error;
            }
        }

        // 显示结果
        function showResult(element, message, type) {
            element.innerHTML = message;
            element.className = 'result-area';
            if (type) element.classList.add(type);
            element.style.display = 'block';
        }

        // 添加历史记录项
        function addHistoryItem(type, title, fileType) {
            const historyList = document.getElementById('historyList');
            const types = {
                'upload': {icon: 'fa-cloud-upload-alt', class: 'upload'},
                'create': {icon: 'fa-file-medical', class: 'create'},
                'append': {icon: 'fa-edit', class: 'append'}
            };
            
            const itemType = types[type] || types['upload'];
            const now = new Date();
            const timeStr = now.toLocaleDateString() + ' ' + now.toLocaleTimeString().substring(0, 5);
            
            // 创建新的历史项
            const historyItem = document.createElement('div');
            historyItem.className = `history-item ${itemType.class}`;
            historyItem.innerHTML = `
                <div class="history-icon">
                    <i class="fas ${itemType.icon}"></i>
                </div>
                <div class="history-details">
                    <div class="history-title">${title}</div>
                    <div class="history-time">${timeStr}</div>
                </div>
            `;
            
            // 添加到列表顶部
            historyList.insertBefore(historyItem, historyList.firstChild);
            
            // 保持最多5条历史记录
            if (historyList.children.length > 5) {
                historyList.removeChild(historyList.lastChild);
            }
        }
    </script>
</body>
</html>